//
//  AppDelegate.m
//  DanoneEA
//
//  Created by apple on 16/8/1.
//  Copyright © 2016年 翔傲科技. All rights reserved.
//

#import "AppDelegate.h"
 

#import "DNLeftDrawerTableVC.h"
#import "DNDataBase.h"
#import "DNUserManager.h"
#import "TTILogFileManager.h"
#import "CatchCrash.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
 
#define APP_SERVER_VERSION @"APP_SERVER_VERSION"


#import "TTILogger.h"
#import "TTILogFormatter.h"

@interface AppDelegate ()<JPUSHRegisterDelegate>


@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    DDLogVerbose(@"---didFinishLaunchingWithOptions: %@", [NSDate date]);
    
    //Add Jery 2016-11-01 注册消息处理函数的处理方法
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    // Senela Add:2016-11-07; for init JPUSH
    [self initAPNs];
    // init Push 
    [JPUSHService setupWithOption:launchOptions
                           appKey:Jpush_AppKey
                          channel:nil
                 apsForProduction:Jpush_isProduction
            advertisingIdentifier:nil];
    [JPUSHService crashLogON];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
    [JPUSHService setBadge:0];
    
    // Senela Add:2016-10-21;
    [self initLogSystem];
    [self initSystemTabbarViewController];
    [self printCurrentLanguage];
    
    

    [[DNDataBase shareInstance] createDatabaseQueue];
//    self.database.logsErrors = YES;
    
    // 初始化系统信息
    [[DNUserManager sharedInstance] initSystemInformationOnce];
    
    [[DNUserManager sharedInstance] setValueInDefault:@"3" withKey:UserDefaultKey_SynchronousDays];
    
    [[DNUserManager sharedInstance] synchronousLocalDataToServer];
    
    
    //FIXME:to be delete
    [[DNUserManager sharedInstance] printDeviceInfo];
    DDLogVerbose(@"IPAddress: %@", [[DNUserManager sharedInstance] getIPAddress]);
    return YES;
}

-(void)initAPNs
{
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
}



-(void)initLogSystem
{
    // 1、将日志打印到Xcode控制台
    [DDLog addLogger:[DDTTYLogger sharedInstance]];

    //2、日志打印到mac的console程序里面
//    [DDLog addLogger:[DDASLLogger sharedInstance]];
    
    //3、将日志保存至文件
    NSString * applicationDocumentsDirectory = [[[[NSFileManager defaultManager]
                                                  URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
    
    
    
    DDLogFileManagerDefault *documentsFileManager = [[TTILogFileManager alloc]
                                                     initWithLogsDirectory:applicationDocumentsDirectory];
    DDFileLogger *fileLogger = [[DDFileLogger alloc] initWithLogFileManager:documentsFileManager];
    fileLogger.rollingFrequency = 60 * 60 * 24 ; // 24 day rolling
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    DDLogInfo(@"logsDirectory: %@", [fileLogger.logFileManager logsDirectory]);
    [DDLog addLogger:fileLogger];
//
//    
//    // 4、自定义日志功能：通过实现该类把日志保存到数据库里面
    TTILogger *logger = [TTILogger new];
    [logger setLogFormatter:[TTILogFormatter new]];
    [DDLog addLogger:logger];
}
 

-(void)printCurrentLanguage
{
    // 取得用户默认信息
    NSUserDefaults *defaults = [ NSUserDefaults standardUserDefaults ]; 
    NSArray *languages = [defaults objectForKey : @"AppleLanguages" ];
    NSString* currentLanguage = [languages objectAtIndex:0];
    DDLogVerbose(@"Current Language：%@",currentLanguage);

}

-(void)initSystemTabbarViewController
{
    UIViewController * leftSideDrawerViewController = [[DNLeftDrawerTableVC alloc] init];
    UINavigationController * leftSideNavController = [[UINavigationController alloc] initWithRootViewController:leftSideDrawerViewController];
    [leftSideNavController setRestorationIdentifier:@"DNLeftNavigationControllerRestorationKey"];
    
    // add right side drawer view controller when current view will appear
    UIViewController * rightSideDrawerViewController = [[DNLeftDrawerTableVC alloc] init];
    UINavigationController * rightSideNavController = [[UINavigationController alloc] initWithRootViewController:rightSideDrawerViewController];
    [rightSideNavController setRestorationIdentifier:@"DNRightNavigationControllerRestorationKey"];
    
    
    _tabBarVC = [[DNTabBarViewController alloc] init];
    
    self.drawerController = [[MMDrawerController alloc]
                             initWithCenterViewController:_tabBarVC
                             leftDrawerViewController:leftSideNavController
                             rightDrawerViewController:rightSideNavController];
    [self.drawerController setShowsShadow:NO];
    [self.drawerController setRestorationIdentifier:@"MMDrawer"];
    [self.drawerController setMaximumRightDrawerWidth:240.0]; 
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    UIColor * tintColor = [UIColor colorWithRed:29.0/255.0
                                          green:173.0/255.0
                                           blue:234.0/255.0
                                          alpha:1.0];
    [self.window setTintColor:tintColor];
    [self.window setRootViewController:self.drawerController];

}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    DDLogVerbose(@"---applicationWillResignActive: %@", [NSDate date]);
    [[DNUserManager sharedInstance] setLastVisitType:ModuleType_None];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    DDLogVerbose(@"---applicationDidBecomeActive: %@", [NSDate date]);
    [[DNUserManager sharedInstance] resetCurrentVCType];

}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
 
// Senela Add:2016-11-07; ADD FOR JPUSH
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    [JPUSHService setTags:nil alias:@"123456" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        DDLogVerbose(@"%d", iResCode);
    }];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    DDLogError(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support －－ 前台收到远程消息
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
//        [JPUSHService resetBadge];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support －－点击远程消息后进入app
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [UIApplication sharedApplication].applicationIconBadgeNumber=0;
        [JPUSHService setBadge:0];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

@end
